<?php

declare(strict_types=1);

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 *  邀请奖励
 */
class InviteRewardLog extends Model
{
    protected $table = 'act_invite_reward_log';

    //充值
    const TYPE_RECHARGE = 1;
    //消费
    const TYPE_CONSUME = 2;
    const TYPE = [
        self::TYPE_RECHARGE => '充值',
        self::TYPE_CONSUME => '收入',
    ];

    /**
     * 邀请分红
     */
    static function getInviteCoin($inviter = 0, $invited = 0)
    {
        $where = [
            'user_id' => $inviter,
            'invited_user_id' => $invited,
            'flag' => 1
        ];
        $data = self::where($where)->select(DB::raw('SUM(reward_coin) as coin'))->first();
        return $data->coin ?: 0;
    }

    /**
     * 添加记录
     */
    static function addRecord($userId = 0, $invitedUserId = 0, $coin = 0, $type = self::TYPE_RECHARGE)
    {
        $model = new self();
        $model->user_id = $userId;
        $model->invited_user_id = $invitedUserId;
        $model->reward_coin = $coin;
        $model->reward_type = $type;
        return $model->saveOrFail() ? 1 : 0;
    }
}
